package com.csx.data.sample.security;

import com.csx.data.sample.security.impl.DefaultDBSecurity;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/10/24 周二 17:02
 */
public class DBSecurityContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {


    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        // 1、mysql/oracle数据库配置解密
        String enabled = environment.getProperty("spring.datasource.encrypt.enabled");
        Map<String, Object> configMap = new HashMap<>();
        if ("true".equals(enabled)) {
            //获取原始密码
            String password = environment.getProperty("spring.datasource.password");

            //去除右括号
            if (password.contains(")")) {
                password = password.replace(")", "");
            }
            //数据库密码解密
            String[] keyAndPassword = password.split("\\(");
            if (keyAndPassword.length == 2) {   //数据源存在加解密配置
                DBSecurity security = new DefaultDBSecurity();
                password = security.decrypt(keyAndPassword[1]);
            } else {   //数据源不存在加解密配置
                password = keyAndPassword[0];
            }

            //设置数据库的配置
//            configMap.put("spring.datasource.password", password);
            System.setProperty("spring.datasource.password", password);
        }

        //将配置加入spring容器中
//        CompositePropertySource composite = new CompositePropertySource("dbConfig");
//        composite.addPropertySource(new MapPropertySource("db", configMap));
//        environment.getPropertySources().addLast(composite);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
